package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.doc.CourseDoc;
import cn.itsource.ymcc.dto.CourseQueryDto;
import cn.itsource.ymcc.mapper.HighlightResultMapper;
import cn.itsource.ymcc.repository.CourseRepository;
import cn.itsource.ymcc.result.AggrPageList;
import cn.itsource.ymcc.result.AggrTermsBucket;
import cn.itsource.ymcc.result.PageList;
import cn.itsource.ymcc.service.ICourseESService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class CourseESServiceImpl implements ICourseESService {

    @Autowired
    private CourseRepository repository;

    @Autowired
    private ElasticsearchRestTemplate template;

    @Autowired
    private HighlightResultMapper highlightResultMapper;

    /**-----------------------------------------------------------------
     * Description：从ES查询课程
     * 1.把dto中的查询条件，转换成ES的查询：NativeSearchQueryBuilder
     * 2.调用repository执行查询，得到Page
     * 3.把ES的Page 转换成 PageList
     *-----------------------------------------------------------------*/
    @Override
    public PageList<CourseDoc> searchCourse(CourseQueryDto dto) {

        //把dto中的查询条件，转换成ES的查询：NativeSearchQueryBuilder
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        //排序
        setSortAndPaging(dto, queryBuilder);

        //设置查询条件
        setQueryParam(dto, queryBuilder);

        //代码块说明：课程名字高亮
        setHighlight(queryBuilder);

        //设置聚合
        setAggr(queryBuilder);

        //执行查询
        AggregatedPage<CourseDoc> page = template.queryForPage(queryBuilder.build(), CourseDoc.class, highlightResultMapper);

        //处理聚合结果
        Map<String, List<AggrTermsBucket>> aggrMap = getAggrResult(page);


        //把ES的Page 转换成 PageList
        return new AggrPageList<CourseDoc>(page.getTotalElements(),page.getContent(),aggrMap);
    }

    @Override
    public void save(CourseDoc doc) {
        repository.save(doc);
    }

    private Map<String, List<AggrTermsBucket>> getAggrResult(AggregatedPage<CourseDoc> page) {
        //用来封装聚合结果
        Map<String,List<AggrTermsBucket>> aggrMap = new HashMap<>();

        //遍历聚合结果
        Aggregations aggregations = page.getAggregations();

        Map<String, Aggregation> stringAggregationMap = aggregations.asMap();

        Set<Map.Entry<String, Aggregation>> entries = stringAggregationMap.entrySet();

        entries.forEach(e->{
            //集合的名字
            String key = e.getKey();
            //集合的值的处理
            ParsedStringTerms value = (ParsedStringTerms)e.getValue();
            List<? extends Terms.Bucket> buckets = value.getBuckets();

            //使用lomda 把  List<StringTerms.Bucket>  转成  List<AggrTermsVo>
            List<AggrTermsBucket> aggrTermsVos = buckets.stream().map(bucket -> {
                return new AggrTermsBucket(bucket.getKeyAsString(), bucket.getDocCount());
            }).collect(Collectors.toList());

            aggrMap.put(key, aggrTermsVos);
        });
        return aggrMap;
    }

    private void setAggr(NativeSearchQueryBuilder queryBuilder) {
        TermsAggregationBuilder gradeNameAgg = AggregationBuilders
                .terms("gradeNameAgg") //聚合名
                .field("gradeName")    //按照机构名聚合
                .order(BucketOrder.count(false))    //按照count排序，倒排
                .size(10);//取前10条

        TermsAggregationBuilder chargeNameAgg = AggregationBuilders
                .terms("chargeNameAgg") //聚合名
                .field("chargeName")    //按照机构名聚合
                .order(BucketOrder.count(false))    //按照count排序，倒排
                .size(10);//取前10条
        TermsAggregationBuilder courseTypeNameAgg = AggregationBuilders
                .terms("courseTypeNameAgg") //聚合名
                .field("courseTypeName")    //按照机构名聚合
                .order(BucketOrder.count(false))    //按照count排序，倒排
                .size(10);//取前10条

        queryBuilder.addAggregation(gradeNameAgg).addAggregation(chargeNameAgg).addAggregation(courseTypeNameAgg);
    }

    private void setHighlight(NativeSearchQueryBuilder queryBuilder) {
        HighlightBuilder.Field  highlightField = new HighlightBuilder.Field("name")
                .preTags("<span style='color:red'>")
                .postTags("</span>");

        queryBuilder.withHighlightFields(highlightField);
    }

    private void setQueryParam(CourseQueryDto dto, NativeSearchQueryBuilder queryBuilder) {

        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //must :课程名，关键字查询
        if(StringUtils.hasLength(dto.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("name", dto.getKeyword()));
            //boolQuery.must(QueryBuilders.multiMatchQuery(dto.getKeyword(),"name","tenantName"));
        }

        //filter :

        //课程类型
        if(dto.getCourseTypeId() != null){
            boolQuery.filter(QueryBuilders.termQuery("courseTypeId", dto.getCourseTypeId()));
        }
        //等级名
        if(StringUtils.hasLength(dto.getGradeName())){
            boolQuery.filter(QueryBuilders.termQuery("gradeName", dto.getGradeName()));
        }
        //最小价格
        if(null != dto.getPriceMin()){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(dto.getPriceMin()));
        }
        //最大价格
        if(null != dto.getPriceMax()){
            boolQuery.filter(QueryBuilders.rangeQuery("price").lte(dto.getPriceMax()));
        }

        queryBuilder.withQuery(boolQuery);
    }

    private void setSortAndPaging(CourseQueryDto dto, NativeSearchQueryBuilder queryBuilder) {
        if(StringUtils.hasLength(dto.getSortField())){

            //默认新品
            String fieldName = null;

            switch (dto.getSortField().toLowerCase()){
                case "xl":fieldName = "saleCount";break;
                case "xp":fieldName = "onlineTime";break;
                case "pl":fieldName = "commentCount";break;
                case "jg":fieldName = "price";break;
                case "rq":fieldName = "viewCount";break;
                default: fieldName = "onlineTime";
            }

            SortOrder sortOrder = SortOrder.DESC;

            if(StringUtils.hasLength(dto.getSortType()) && dto.getSortType().toLowerCase().equals("asc")){
                sortOrder = SortOrder.ASC;
            }

            //排序
            queryBuilder.withSort(SortBuilders.fieldSort(fieldName).order(sortOrder));
        }

        /**--------------------------------------------------------
        * 代码块说明：分页
        --------------------------------------------------------**/
        queryBuilder.withPageable(PageRequest.of(dto.getPage() - 1, dto.getRows()));

    }
}
